package com.xc.stock.dto.query;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.ag.utils.CollectionUtils;
import com.ag.utils.Jsons;
import com.ag.utils.NumberUtils;
import com.ag.utils.SysConstant;
import com.ag.utils.SysConstant.YesNoEnum;
import com.ag.utils.vo.TimeQuery;
import com.google.common.collect.Lists;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.Predicate;
import com.xc.stock.constant.AccountActionEnum;
import com.xc.stock.constant.AccountType;
import com.xc.stock.constant.RoleEnum;
import com.xc.stock.infrastructure.db.po.QAccountActionPO;
import com.xc.stock.utils.ConditionBuilder;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

@Data
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@EqualsAndHashCode(callSuper = false)
public class AccountActionQuery extends TimeQuery {
	String accountNo;
	String accountNoList;
	String actionList;
	AccountType accountType;
	Integer agentId;
	Integer filterRemove;
	Integer actionStatus;
	String destId;
	RoleEnum role;
	String agentMemberNo;
	AccountActionEnum action;
	
	String orderSpecifier;
	public OrderSpecifier<?> orderSpecifier() {
		QAccountActionPO q = QAccountActionPO.accountActionPO;
		if ("idAsc".equals(orderSpecifier)) {
			return q.id.asc();
		}

		return q.id.desc();
	}
	
	public Predicate where() {
		return where(Lists.newArrayList());
	}
	
	public Predicate where(List<Path<?>> ignorePath) {
		super.check();
		QAccountActionPO q = QAccountActionPO.accountActionPO;
		ConditionBuilder builder = ConditionBuilder.builder();
		if(CollectionUtils.isNotEmpty(Jsons.toListAnyway(accountNoList, String.class))) {
			builder.and(q.accountNo.in(Jsons.toList(accountNoList, String.class)));
		}
		
		if(StringUtils.isNotBlank(accountNo)) {
			builder.and(q.accountNo.eq(accountNo));
		}
		
		if(StringUtils.isNotBlank(destId)) {
			builder.and(q.destId.eq(destId));
		}
		
		if(NumberUtils.isValid(agentId)) {
			builder.and(q.agentId.eq(agentId));
		}
		
		if(YesNoEnum.isYes(filterRemove)) {
			builder.and(q.status.eq(SysConstant.STATUS_NORMAL));
		}
		
		if(StringUtils.isNotBlank(agentMemberNo)) {
			builder.and(q.agentMemberNo.eq(agentMemberNo));
		}
		
		if(CollectionUtils.isNotEmpty(Jsons.toListAnyway(actionList, String.class))) {
			builder.and(q.action.in(Jsons.toList(actionList, String.class)));
		}
		
		if(action != null) {
			builder.and(q.action.eq(action.code()));
		}
		
		if(role != null) {
			builder.and(q.role.eq(role.code()));
		}
		
		if(accountType != null) {
			builder.and(q.accountType.eq(accountType.code()));
		}
		
		if(actionStatus != null) {
			builder.and(q.actionStatus.eq(actionStatus));
		}
		
		if(dateStart() != null) {
			builder.and(q.createAt.between(dateStart(), dateEnd()));
		}

		return builder.build();
	}
}
